package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AliPayConfig;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.rabbit.constant.RabbitConst;
import com.atguigu.gmall.rabbit.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 沙箱支付账号：dbddkv8031@sandbox.com
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class paymentApicontroller {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private RabbitService rabbitService;

    public static final String REDIRECT = "redirect:";

    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submitAlipay(@PathVariable  Long orderId) throws AlipayApiException {

        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        paymentService.savePayInfo(orderInfo, PaymentType.ALIPAY.name());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map map = new HashMap();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",orderInfo.getTotalAmount());
        map.put("subject",orderInfo.getTradeBody());
        request.setReturnUrl(aliPayConfig.getReturn_url());
        request.setNotifyUrl(aliPayConfig.getNotify_url());
        request.setBizContent(JSONObject.toJSONString(map));
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return response.getBody();
        } else {
            System.out.println("调用失败");
            return null;
        }

    }

    @GetMapping("/callback/return")
    public String callbackReturn(){

        return REDIRECT+aliPayConfig.getReturn_order_url();
    }

    @PostMapping("/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam  Map<String, String> paramsMap){
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramsMap,aliPayConfig.getAlipay_public_key(),
                    aliPayConfig.getCharset(),aliPayConfig.getSigntype());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("paramsMap="+paramsMap);
        String trade_status = paramsMap.get("trade_status");
        String out_trade_no = paramsMap.get("out_trade_no");
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            if("TRADE_SUCCESS".equals(trade_status)||
                    "TRADE_FINISHED".equals(trade_status)){
              PaymentInfo paymentInfo =   paymentService.getPaymentInfo(out_trade_no,
                      PaymentType.ALIPAY.name());
                if(paymentInfo.getPaymentStatus()==PaymentStatus.PAID.name()||
                paymentInfo.getPaymentStatus()==PaymentStatus.ClOSED.name()){
                    return "failure";
                }
                paymentService.paySuccess(paymentInfo,paramsMap);
                rabbitService.sendMessage(RabbitConst.EXCHANGE_DIRECT_PAYMENT_PAY,RabbitConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());
                return "success";

            }
            return "success";
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }

    }

//    //修改订单状态
//    @GetMapping("/updateOrderStatus/{orderId}")
//    @ResponseBody
//    public void updateOrderStatus(@PathVariable Long orderId){
//        rabbitService.sendMessage(RabbitConst.EXCHANGE_DIRECT_PAYMENT_PAY,RabbitConst.ROUTING_PAYMENT_PAY,orderId);
//
//    }


}
